#include <CondVar.hh>
#include "FactoryTest.hh"
#include <Task.hh>
#include <TimeoutQueue.hh>
#include <IPFactory.hh>
#include <stdlib.h>

#include <Average.hh>
#include <StressTask.hh>

Mutex CountTask::Key;
Number CountTask::Count = 0;

ResultOf FactoryTest::testBaseCase(Factory* Target)
{
	ResultOf Result;
// 	Result = Target->run(10, 200);
	Result = Target->run(1, 200);
	checkErrorWR(Result, "Fail Target->run.");
	
	Task* NewTask;
	for (Number LC = 0; LC < LoopCount; LC++)
	{
		NewTask = Task::generate(StressTaskType);
		checkNullWR(NewTask, "NewTask is NULL.");
		
		Result = Target->fetchTask(NewTask);
		checkErrorWR(Result, "Fail Target->fetchTask.");
		
		switch (random() % 8)
		{
			case 0:
			case 1:
			case 2:
			case 3:
				break;
			
			case 4:
				delay(100);
				break;
			
			case 5:
				delay(1000);
				break;
			
			case 6:
				delay(2000);
				break;
			
			case 7:
				delay(10000);
				break;
		}
	}
	
	Result = Target->stop();
	checkErrorWR(Result, "Fail Target->stop.");
	
// 	if (Target->tellNumOfEmployee() != 0)
// 	{
// 		notifyError(Target->tellNumOfEmployee(), "Not exiting completely.");
// 		return RETURN_ERROR;
// 	}
// 	
// 	if (CountTask::report() != LoopCount)
// 	{
// 		notifyError(CountTask::report(), "The resulting value is incorrect.");
// 		return RETURN_ERROR;
// 	}
	
	return RETURN_OK;
}

ResultOf testFactory()
{
	TimeoutQueue Queue;
	Queue.setTimeout(300000);
	
	IPFactory MyFactory(&Queue);
	MyFactory.setIntervalOfWatchdog(100000);
	
	ResultOf Result;
	FactoryTest Test;
	
	Result = Test.testBaseCase(&MyFactory);
	checkErrorWR(Result, "Fail Test.testBaseCase.");
	
	printf("%g\n", StressTask::tellResponseTime());

// 	fprintf(stderr, "Factory: Test success.\n");
	return RETURN_OK;
}
